﻿using System.Net;
using System;
using System.Text;
using System.IO;
using OAuth;


namespace Caliburn.Micro.WP7DoubanFM {
    public class MainPageViewModel {
        readonly INavigationService navigationService;

        public MainPageViewModel(INavigationService navigationService) {
            this.navigationService = navigationService;
        }

        public void GotoPageTwo()
        {
            OAuthBase oauth = new OAuthBase();
            Uri oauth_basic_url = new Uri("http://www.douban.com/service/auth/request_token");
            string apikey = "020f18e6fec6911a062d4ab4fc53b34e";  //api key
            string apiKeySecret = "a7d82460ce52910d";            //私钥

            string timestamp = oauth.GenerateTimeStamp();

            string nonce = oauth.GenerateNonce();

            string oauth_signature_method = "HMAC-SHA1";

            string normalizeUrl, normalizedRequestParameters;

            string oauth_signature = oauth.GenerateSignature(oauth_basic_url,
                apikey, apiKeySecret, string.Empty, string.Empty, "GET", timestamp, nonce, string.Empty, out normalizeUrl, out normalizedRequestParameters);

            oauth_signature = HttpUtility.UrlEncode(oauth_signature);

            StringBuilder requestToken = new StringBuilder(oauth_basic_url.ToString());
            requestToken.AppendFormat("?oauth_consumer_key={0}&", apikey);
            requestToken.AppendFormat("oauth_nonce={0}&", nonce);
            requestToken.AppendFormat("oauth_timestamp={0}&", timestamp);
            requestToken.AppendFormat("oauth_signature_method={0}&", oauth_signature_method);
            requestToken.AppendFormat("oauth_version={0}&", "1.0"); 
            requestToken.AppendFormat("oauth_signature={0}", oauth_signature);
            
            WebRequest request = WebRequest.Create(requestToken.ToString());
            request.BeginGetResponse(new AsyncCallback(HandleRequestTokenResponse), request);
        }

        protected static void HandleRequestTokenResponse(IAsyncResult asyncResult)
        {
         HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;//获取异步操作返回的的信息
         WebResponse response = request.EndGetResponse(asyncResult);//结束对 Internet 资源的异步请求
         Stream streamResult = response.GetResponseStream();

         StreamReader reader = new StreamReader(streamResult);
         string contents = reader.ReadToEnd();  //"oauth_token_secret=2c41c7b61d1d8c60&oauth_token=f5ab97ca2c0ee301e102c75e842ca903"

         //TODO: Get oauth_token_secret and oauth_token
        }
    }
}